package com.yuanian.ecsplus.advice;

import com.yuanian.ecsplus.annotation.controller.ControllerResult;
import com.yuanian.ecsplus.annotation.controller.NotControllerResult;
import com.yuanian.ecsplus.enums.OperateType;
import com.yuanian.ecsplus.threadlocal.ThreadLocalMap;
import com.yuanian.infrastructure.util.model.ResultValue;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.lang.annotation.Annotation;

@RestControllerAdvice
public class ControllerResultAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        Annotation notControllerResult = returnType.getMethodAnnotation(NotControllerResult.class);
        //是否有ControllerResult注解
        if (notControllerResult != null) {
            return false;
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //自身已是ResultValue
        if (body instanceof ResultValue) {
            return body;
        }
        ControllerResult controllerResult = returnType.getMethodAnnotation(ControllerResult.class);
        //没有ControllerResult，默认为QUERY
        OperateType operateType;
        if (controllerResult == null) {
            operateType = OperateType.QUERY;
        } else {
            operateType = controllerResult.operateType();
        }

        try {
            if (operateType != OperateType.QUERY && operateType != OperateType.CREATE) {
                return new ResultValue(body, true, operateType.getDesc() + "成功");
            } else {
                //查询不加提示
                return new ResultValue(body);
            }
        } finally {
            ThreadLocalMap.clear();
        }
    }

}
